package net.lainiao.manager.shiro;

import net.lainiao.base.model.ShiroRole;
import net.lainiao.base.model.ShiroUser;
import net.lainiao.service.service.ShiroRoleService;
import net.lainiao.service.service.ShiroUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2017/1/19.
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private ShiroUserService shiroUserService;
    @Resource
    private ShiroRoleService shiroRoleService;
    @Resource
    private SuperUser superUser;
    /***
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        //根据自己系统规则的需要编写获取授权信息，这里为了快速入门只获取了用户对应角色的资源url信息
        String username = (String) pc.fromRealm(getName()).iterator().next();
        if (username != null) {
              List<ShiroRole> roles=null;
              if(superUser.getUsername().equals(username)){
                    roles=shiroRoleService.getAllRoles();
              }
              else{
                    roles=shiroRoleService.getRolesForUser(username);
              }

              if(roles!=null&&roles.size()>0){
                  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                  for(ShiroRole role:roles){
                    info.addRole(role.getRolename());
                  }
                  return info;
              }
        }
        return null;
    }
    /***
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) at;
        String username = token.getUsername();
        char[] pwd = token.getPassword();
        String password=new String(pwd);
        if(superUser.isAdmin(username,password)){
            return new SimpleAuthenticationInfo(username,password,getName());
        }
        ShiroUser user=shiroUserService.getUserByUserName(username);
        if(user!=null){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
        }
        return null;
    }
}
